package com.banksoft.front.bean;


import com.alibaba.fastjson.JSON;
import com.banksoft.admin.bean.TextMessage;
import com.banksoft.util.StringUtil;
import com.banksoft.util.XmlUtil;
import net.sf.json.JSONObject;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.xml.sax.InputSource;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 14-8-8.
 */
public class MessageUtil {

    public static Map<String, String> parseXml(HttpServletRequest request) throws DocumentException, IOException {
        // 将解析结果存储在HashMap中
        Map<String, String> map = new HashMap<String, String>();

        // 从request中取得输入流
        InputStream inputStream = request.getInputStream();
        // 读取输入流
        SAXReader reader = new SAXReader();
        Document document = reader.read(inputStream);
        // 得到xml根元素
        Element root = document.getRootElement();
        // 得到根元素的所有子节点
        List<Element> elementList = root.elements();

        // 遍历所有子节点
        for (Element e : elementList)
            map.put(e.getName(), e.getText());

        // 释放资源
        inputStream.close();
        inputStream = null;
        return map;
    }


    public static Map<String, String> parseXmlByString(String xmlString) throws DocumentException, IOException {
        // 将解析结果存储在HashMap中
        Map<String, String> map = new HashMap<String, String>();
        StringReader read = new StringReader(xmlString);
        //创建新的输入源SAX 解析器将使用 InputSource 对象来确定如何读取 XML 输入
        InputSource source = new InputSource(read);
        // 读取输入流
        SAXReader reader = new SAXReader();
        Document document = reader.read(source);
        // 得到xml根元素
        Element root = document.getRootElement();
        // 得到根元素的所有子节点
        List<Element> elementList = root.elements();

        // 遍历所有子节点
        for (Element e : elementList)
            map.put(e.getName(), e.getText());

        return map;
    }

    //组装文本消息
    public static String keMessageToXml(TextMessage textMessage) {
        JSONObject json = new JSONObject();
        json.put("touser",textMessage.getToUserName());
        json.put("msgtype",textMessage.getMsgType());
        JSONObject textJSon = new JSONObject();
        textJSon.put("content",textMessage.getContent());
        json.put("text",textJSon);
        return json.toString();
    }

//    //组装文本消息
   public static String textMessageToXml(TextMessage textMessage) {
     String message = "<xml>" +
               "<ToUserName><![CDATA["+textMessage.getToUserName()+"]]></ToUserName>" +
               "<FromUserName><![CDATA["+textMessage.getFromUserName()+"]]></FromUserName>" +
               "<CreateTime>"+textMessage.getCreateTime()+"</CreateTime>" +
               "<MsgType><![CDATA["+textMessage.getMsgType()+"]]></MsgType>" +
               "<Content><![CDATA["+textMessage.getContent()+"]]></Content>" +
               "</xml>";
       return message;
    }

    //组装图片消息
    public static String imageMessageToXml(TextMessage textMessage) {
//        *
//         * <xml>
//         <ToUserName><![CDATA[toUser]]></ToUserName>
//         <FromUserName><![CDATA[fromUser]]></FromUserName>
//         <CreateTime>12345678</CreateTime>
//         <MsgType><![CDATA[image]]></MsgType>
//         <Image>
//         <MediaId><![CDATA[media_id]]></MediaId>
//         </Image>
//         </xml>
//
        String message = "<xml>" +
                "<ToUserName><![CDATA[" + textMessage.getToUserName() + "]]></ToUserName>" +
               "<FromUserName><![CDATA[" + textMessage.getFromUserName() + "]]></FromUserName>" +
               "<CreateTime>" + textMessage.getCreateTime() + "</CreateTime>" +
                "<MsgType><![CDATA[" + textMessage.getMsgType() + "]]></MsgType>" +
                "<Image>" +
                "<MediaId><![CDATA[" + textMessage.getMediaId() + "]]></MediaId>" +
                "</Image>" +
                "</xml>";
        return message;
    }


    //组装调用统一支付接口时所需要的数据
    public static String tyZfToXml(TyZf tyZf) {
        String message = "<xml>" +
                "<appid><![CDATA[" + tyZf.getAppid() + "]]></appid>" +
                "<mch_id><![CDATA[" + tyZf.getMch_id() + "]]></mch_id>" +
                "<nonce_str><![CDATA[" + tyZf.getNonce_str() + "]]></nonce_str>" +
                "<sign><![CDATA[" + tyZf.getSign() + "]]></sign>" +
                "<body><![CDATA[" + tyZf.getBody() + "]]></body>" +
                "<out_trade_no><![CDATA[" + tyZf.getOut_trade_no() + "]]></out_trade_no>" +
                "<total_fee><![CDATA[" + tyZf.getTotal_fee() + "]]></total_fee>" +
                "<spbill_create_ip><![CDATA[" + tyZf.getSpbill_create_ip() + "]]></spbill_create_ip>" +
                "<notify_url><![CDATA[" + tyZf.getNotify_url() + "]]></notify_url>" +
                "<trade_type><![CDATA[" + tyZf.getTrade_type() + "]]></trade_type>";
        if (!StringUtil.isNullOrEmpty(tyZf.getDevice_info())) {
            message = message + "<device_info><![CDATA[" + tyZf.getDevice_info() + "]]></device_info>";
        }
        if (!StringUtil.isNullOrEmpty(tyZf.getAttach())) {
            message = message + "<attach><![CDATA[" + tyZf.getAttach() + "]]></attach>";
        }
        if (!StringUtil.isNullOrEmpty(tyZf.getTime_start())) {
            message = message + "<time_start><![CDATA[" + tyZf.getTime_start() + "]]></time_start>";
        }
        if (!StringUtil.isNullOrEmpty(tyZf.getTime_expire())) {
            message = message + "<time_expire><![CDATA[" + tyZf.getTime_expire() + "]]></time_expire>";
        }
        if (!StringUtil.isNullOrEmpty(tyZf.getGoods_tag())) {
            message = message + "<goods_tag><![CDATA[" + tyZf.getGoods_tag() + "]]></goods_tag>";
        }
        if (!StringUtil.isNullOrEmpty(tyZf.getOpenid())) {
            message = message + "<openid><![CDATA[" + tyZf.getOpenid() + "]]></openid>";
        }
        if (!StringUtil.isNullOrEmpty(tyZf.getProduct_id())) {
            message = message + "<product_id><![CDATA[" + tyZf.getProduct_id() + "]]></product_id>";
        }
        message = message + "</xml>";
        return message;
    }

    //组装调用微信通用通知接口后返回给微信的信息数据
    public static String tyNoticeToXml(TyNoticeSj tyNoticeSj) {
        String message = "<xml>" +
                "<return_code><![CDATA[" + tyNoticeSj.getReturn_code() + "]]></return_code>";
        if(!StringUtil.isNullOrEmpty(tyNoticeSj.getReturn_msg())) {
            message = message +  "<return_msg><![CDATA[" + tyNoticeSj.getReturn_msg() + "]]></return_msg>";
        }
        message = message + "</xml>";
        return message;
    }

    /**
     *
     */
    public static String getUnifiedOrderXml(TyZf dto){
        org.jdom.Document doc = new org.jdom.Document();
        org.jdom.Element root = new org.jdom.Element("xml");

        org.jdom.Element appId = new org.jdom.Element("appid");
        appId.setText(dto.getAppid());
        root.addContent(appId);

        org.jdom.Element mch_id = new org.jdom.Element("mch_id");
        mch_id.setText(dto.getMch_id());
        root.addContent(mch_id);

        if(StringUtil.isNotNull(dto.getDevice_info())){
            org.jdom.Element device_info = new org.jdom.Element("device_info");
            device_info.setText(dto.getDevice_info());
            root.addContent(device_info);
        }
        org.jdom.Element nonce_str = new org.jdom.Element("nonce_str");
        nonce_str.setText(dto.getNonce_str());
        root.addContent(nonce_str);

        org.jdom.Element sign = new org.jdom.Element("sign");
        sign.setText(dto.getSign());
        root.addContent(sign);

        org.jdom.Element body = new org.jdom.Element("body");
        body.setText(dto.getBody());
        root.addContent(body);

        if(StringUtil.isNotNull(dto.getDetail())) {
            org.jdom.Element detail = new org.jdom.Element("detail");
            detail.setText(dto.getDetail());
            root.addContent(detail);
        }
        if(StringUtil.isNotNull(dto.getAttach())){
            org.jdom.Element attach = new org.jdom.Element("attach");
            attach.setText(dto.getAttach());
            root.addContent(attach);
        }

        org.jdom.Element out_trade_no = new org.jdom.Element("out_trade_no");
        out_trade_no.setText(dto.getOut_trade_no());
        root.addContent(out_trade_no);

        if(StringUtil.isNotNull(dto.getFee_type())){
            org.jdom.Element fee_type = new org.jdom.Element("fee_type");
            fee_type.setText(dto.getFee_type());
            root.addContent(fee_type);
        }

        org.jdom.Element total_fee = new org.jdom.Element("total_fee");
        total_fee.setText(dto.getTotal_fee()+"");
        root.addContent(total_fee);

        org.jdom.Element spbill_create_ip = new org.jdom.Element("spbill_create_ip");
        spbill_create_ip.setText(dto.getSpbill_create_ip());
        root.addContent(spbill_create_ip);

        if(StringUtil.isNotNull(dto.getTime_start())){
            org.jdom.Element time_start = new org.jdom.Element("time_start");
            time_start.setText(dto.getTime_start());
            root.addContent(time_start);
        }
        if(StringUtil.isNotNull(dto.getTime_expire())){
            org.jdom.Element time_expire = new org.jdom.Element("time_expire");
            time_expire.setText(dto.getTime_expire());
            root.addContent(time_expire);
        }
        if(StringUtil.isNotNull(dto.getGoods_tag())){
            org.jdom.Element goods_tag = new org.jdom.Element("goods_tag");
            goods_tag.setText(dto.getGoods_tag());
            root.addContent(goods_tag);
        }

        org.jdom.Element notify_url = new org.jdom.Element("notify_url");
        notify_url.setText(dto.getNotify_url());
        root.addContent(notify_url);

        org.jdom.Element trade_type = new org.jdom.Element("trade_type");
        trade_type.setText(dto.getTrade_type());
        root.addContent(trade_type);

        if(StringUtil.isNotNull(dto.getProduct_id())){
            org.jdom.Element product_id = new org.jdom.Element("product_id");
            product_id.setText(dto.getProduct_id());
            root.addContent(product_id);
        }

        if(StringUtil.isNotNull(dto.getLimit_pay())){
            org.jdom.Element limit_pay = new org.jdom.Element("limit_pay");
            limit_pay.setText(dto.getLimit_pay());
            root.addContent(limit_pay);
        }
        if(StringUtil.isNotNull(dto.getOpenid())){
            org.jdom.Element openid = new org.jdom.Element("openid");
            openid.setText(dto.getOpenid());
            root.addContent(openid);
        }
        doc.addContent(root);
        return XmlUtil.formatDocToStr(doc).toString();
    }


    public static OrderResult parseOrderResult(String str){
        OrderResult result = null;
        try{
            org.jdom.Document doc = XmlUtil.parseStrToDoc(str);
            org.jdom.Element root = doc.getRootElement();
            result = new OrderResult();

            org.jdom.Element return_code = root.getChild("return_code");
            result.setReturn_code(return_code.getText());
            org.jdom.Element return_msg = root.getChild("return_msg");
            if(return_msg!=null)
                result.setReturn_msg(return_msg.getText());
            if(return_code.getText().equals("SUCCESS")){//请求成功后
                org.jdom.Element appid = root.getChild("appid");
                result.setAppid(appid.getText());

                org.jdom.Element mch_id = root.getChild("mch_id");
                result.setMch_id(mch_id.getText());

                org.jdom.Element device_info = root.getChild("device_info");
                if(device_info!=null)
                  result.setDevice_info(device_info.getText());

                org.jdom.Element nonce_str = root.getChild("nonce_str");
                result.setNonce_str(nonce_str.getText());

                org.jdom.Element sign = root.getChild("sign");
                result.setSign(sign.getText());

                org.jdom.Element result_code = root.getChild("result_code");
                result.setResult_code(result_code.getText());

                org.jdom.Element err_code = root.getChild("err_code");
                if(err_code!=null)
                    result.setErr_code(err_code.getText());
                org.jdom.Element err_code_des = root.getChild("err_code_des");
                if(err_code_des!=null)
                    result.setErr_code_des(err_code_des.getText());
                if(result_code.getText().equals("SUCCESS")){
                    org.jdom.Element trade_type = root.getChild("trade_type");
                    result.setTrade_type(trade_type.getText());

                    org.jdom.Element prepay_id = root.getChild("prepay_id");
                    result.setPrepay_id(prepay_id.getText());

                    org.jdom.Element code_url = root.getChild("code_url");
                    if(code_url!=null)
                        result.setCode_url(code_url.getText());
                }
             }

        }catch (Exception e){
            e.printStackTrace();
        }
        return result;
    }

    public static NotifyOrder parseNotifyOrder(org.jdom.Document doc){
        NotifyOrder order = new NotifyOrder();
        try{
            org.jdom.Element root = doc.getRootElement();

            org.jdom.Element return_code = root.getChild("return_code");
            order.setReturn_code(return_code.getText());

            org.jdom.Element return_msg = root.getChild("return_msg");
            if(return_msg!=null)
                order.setReturn_msg(return_msg.getText());
            if(return_code.getText().equals("SUCCESS")){
                org.jdom.Element appid = root.getChild("appid");
                order.setAppid(appid.getText());

                org.jdom.Element mch_id = root.getChild("mch_id");
                order.setMch_id(mch_id.getText());

                org.jdom.Element device_info = root.getChild("device_info");
                if(device_info!=null)
                    order.setDevice_info(device_info.getText());
                org.jdom.Element nonce_str = root.getChild("nonce_str");
                order.setNonce_str(nonce_str.getText());

                org.jdom.Element sign = root.getChild("sign");
                order.setSign(sign.getText());

                org.jdom.Element result_code = root.getChild("result_code");
                order.setResult_code(result_code.getText());
                org.jdom.Element err_code = root.getChild("err_code");
                if(err_code!=null)
                    order.setErr_code(err_code.getText());

                org.jdom.Element err_code_des = root.getChild("err_code_des");
                if(err_code_des!=null)
                    order.setErr_code_des(err_code_des.getText());
                org.jdom.Element openid = root.getChild("openid");
                order.setOpenid(openid.getText());

                org.jdom.Element is_subscribe = root.getChild("is_subscribe");
                if(is_subscribe!=null)
                    order.setIs_subscribe(is_subscribe.getText());

                org.jdom.Element trade_type = root.getChild("trade_type");
                order.setTrade_type(trade_type.getText());

                org.jdom.Element bank_type = root.getChild("bank_type");
                order.setBank_type(bank_type.getText());

                org.jdom.Element total_fee = root.getChild("total_fee");
                order.setTotal_fee(Integer.parseInt(total_fee.getText()));

                org.jdom.Element fee_type = root.getChild("fee_type");
                if(fee_type!=null)
                    order.setFee_type(fee_type.getText());
                org.jdom.Element cash_fee = root.getChild("cash_fee");
                order.setCash_fee(Integer.parseInt(cash_fee.getText()));

                org.jdom.Element cash_fee_type = root.getChild("cash_fee_type");
                if(cash_fee_type!=null)
                    order.setCash_fee_type(cash_fee_type.getText());
                org.jdom.Element coupon_fee = root.getChild("coupon_fee");
                if(coupon_fee!=null)
                    order.setCoupon_fee(Integer.parseInt(coupon_fee.getText()));

                org.jdom.Element coupon_count = root.getChild("coupon_count");
                if(coupon_count!=null)
                    order.setCoupon_count(Integer.parseInt(coupon_count.getText()));

                org.jdom.Element coupon_id_$n = root.getChild("coupon_id_$n");
                if(coupon_id_$n!=null)
                    order.setCoupon_id_$n(coupon_id_$n.getText());
                org.jdom.Element coupon_fee_$n = root.getChild("coupon_fee_$n");
                if(coupon_fee_$n!=null)
                    order.setCoupon_fee_$n(Integer.parseInt(coupon_fee_$n.getText()));

                org.jdom.Element transaction_id = root.getChild("transaction_id");
                order.setTransaction_id(transaction_id.getText());

                org.jdom.Element out_trade_no = root.getChild("out_trade_no");
                order.setOut_trade_no(out_trade_no.getText());

                org.jdom.Element attach = root.getChild("attach");
                if(attach!=null)
                    order.setAttach(attach.getText());
                org.jdom.Element time_end = root.getChild("time_end");
                order.setTime_end(time_end.getText());
            }
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
        return order;
    }

    /**
     * 格式化通知结果
     * @param result
     * @return
     */
    public static String getNotifyResult(BaseResult result){
        org.jdom.Document doc = new org.jdom.Document();
        org.jdom.Element root = new org.jdom.Element("xml");
        org.jdom.Element return_code = new org.jdom.Element("return_code");
        return_code.setText(result.getReturn_code());
        org.jdom.Element return_msg = new org.jdom.Element("return_msg");
        return_msg.setText(result.getReturn_msg());
        root.addContent(return_code);
        root.addContent(return_msg);
        doc.addContent(root);

        return XmlUtil.formatDocToStr(doc).toString();
    }




}





























